package com.manage.competition.service.impl;

import com.manage.competition.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Create with IDEA
 *
 * @Author: gitee.com/KamisamaXX
 * @Date: Create in 16:22 2019/3/27
 * @Description:
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {
    
    static private String PATH = "F:/Github/competition/src/main/resources/upload/image/";

    private String UploadContext(MultipartFile multipartFile,String path){
        String fileName = multipartFile.getOriginalFilename();
        //扩展名
        //abc.jpg
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;
        log.info("开始上传文件,上传文件的文件名:{},上传的路径:{},新文件名:{}",fileName,PATH,uploadFileName);
        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile = new File(path,uploadFileName);


        try {
            multipartFile.transferTo(targetFile);
        }catch (IOException e){
            log.error("上传文件异常",e);
            return null;
        }
        return targetFile.getName();
    }

    @Override
    public String upload(MultipartFile multipartFile){
        return UploadContext(multipartFile,PATH);
    }

    @Override
    public Boolean delete(String filename) {
        File targetFile = new File(PATH,filename);
        return targetFile.delete();
    }

    @Override
    public String upload(MultipartFile multipartFile,String path){
        if (path!=null){
            return UploadContext(multipartFile,PATH+path);
        }
        return this.upload(multipartFile);
    }

    @Override
    public Boolean delete(String filename,String path) {
        File targetFile = new File(PATH+path,filename);
        return targetFile.delete();
    }
}
